<template>
  <div id="app">
    <el-card shadow="always">

      <el-form :inline="true" size="medium" :model="studentSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="editStudent" icon="el-icon-plus">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-delete" plain @click="deleteStudent" >批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="studentList"
          style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            label="学号"
            prop="sid"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="姓名"
            align="center"
            prop="sname">
        </el-table-column>
        <el-table-column
            label="性别"
            align="center"
            prop="sex">
        </el-table-column>
        <el-table-column
            label="年龄"
            align="center"
            prop="age">
        </el-table-column>
        <el-table-column
            label="住址"
            align="center"
            prop="addr">
        </el-table-column>
        <el-table-column
            label="所在班级"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteStudent(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </el-card>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">

      <el-form :model="student" :rules="studentrules" ref="ruleForm">
        <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="student.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="student.sex" label="男">男</el-radio>
          <el-radio v-model="student.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="student.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生住址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="student.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在班级" prop="cid" :label-width="formLabelWidth" style="width: 1200px">
          <el-select v-model="student.cid" placeholder="请选择所在班级" >
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStudent">确 定</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import studentApi from "@/api/student"
import classesApi from "@/api/classes"
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (value===''||value.length==0) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value > 200|| value<1) {
            callback(new Error('年龄在1岁到200岁之间'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      studentList: [],
      page:1,
      pageSize:5,
      total:100,
      studentSearch:{},

      classesList: [],
      dialogFormVisible:false,
      sids:[],
      multipleSelection: [],
      formLabelWidth:'100px',
      student: {},
      studentrules: {
        sname: [
          { required: true, message: '请输入学生名称', trigger: 'blur' },

        ],
        sex: [
          { required: true, message: '请选择学生性别', trigger: 'change' }
        ],
        age: [
          { validator: checkAge, trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '请输入学生住址', trigger: 'blur'  }
        ],
        cid: [
          {  required: true, message: '请选择学生班级', trigger: 'change' }
        ]
      },
      title: '添加学生',

    }
  },
  created() {


    this.search1()
    this.findAllClasses()
  },

  methods: {

    async findStudents() {
      const {data:res} = await studentApi.findAllStudents()
      console.log(res)
      if (data.code === 200) {
        this.studentList = res.data.list
      }
    },

    async findByPage() {
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },

    async findAllClasses() {
      const {data:res} = await classesApi.findClasses()
      console.log(res)
      if (res.code === 200) {
        this.classesList = res.data.list
      }
    },

    async search(){
      const {data:res} = await studentApi.search(1,this.pageSize,this.studentSearch)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
      this.page=1
    },
    async search1(){
      const {data:res} = await studentApi.search(this.page,this.pageSize,this.studentSearch)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },

    editStudent(){
      this.title='添加学生';
      this.student={};
      this.dialogFormVisible = true
    },

    async saveStudent(){
      this.$refs.ruleForm.validate(async valid => {
            let url = "/student/save"
            let method = "post"
            if(this.student.sid){
              url = "/student/update"
              method = "put"}


        if (valid) {
          const {data:res} = await studentApi.save(url,method,this.student)

          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration:1000,
              onClose: () => {

                this.dialogFormVisible = false

                this.search1()
              }
            })
          }else{
            this.$message({
              type: 'error',
              message: res.message,
              duration:1000
            })
          }

          console.log('验证成功');
        } else {
          console.log('验证失败');
          return false;
        }
      });

    },
    async deleteStudent(index, row){
      this.sids = []
      if(row){
        this.sids.push(row.sid)
      }else{
        this.sids = this.multipleSelection.map(m => m.sid)
      }
      if(this.sids.length==0)
      {
        this.$message({
          type: 'warning',
          message: '没有选择要删除的学生',
          duration: 1000
        });
        return;

      }
      this.$confirm(`是否真的要删除学号为${this.sids}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        studentApi.delete(this.sids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  duration:1000,
                  onClose: () => {

                    _this.search1()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message,
                  duration:1000
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleEdit(index, row) {

      this.title='修改学生';
      this.student=row;
      console.log(this.student);
      this.dialogFormVisible=true;


    },

    // 每页大小改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;

      this.search1()
    },
    // 当前页改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;

      this.search1()
    },
    // 选择学生改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
}
</script>
<style>
.el-card{
  width: 90%;
//margin: 0 auto;
}
#app{
  display: flex;
  justify-content: center;
}
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
</style>
